<template>
  <section 
    id="navbar" 
    class="w-full z-50 transition-all duration-300"
    :style="{
      backgroundColor: isScrolled ? scrolledBgColor : defaultBgColor,
      boxShadow: isScrolled ? scrolledShadow : 'none'
    }"
  >
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
      <div class="flex justify-between items-center py-4">
        <!-- Logo -->
        <a 
          :href="logoLink" 
          class="flex items-center space-x-2"
          @click.prevent="handleLogoClick()"
        >
          <div 
            class="w-10 h-10 rounded-lg flex items-center justify-center"
            :style="{ backgroundColor: primaryColor }"
          >
            <img 
              v-if="logoText" 
              :src="logoText" 
              alt="Logo" 
              class="w-10 h-10 object-contain"
            />
          </div>
          <span 
            class="text-xl font-bold"
            :style="{ color: logoColor }"
          >
            {{ brandName }}
          </span>
        </a>
        
        <!-- 桌面导航 -->
        <nav class="hidden md:flex items-center space-x-8">
          <a 
            v-for="(item, index) in navItems" 
            :key="index"
            :href="item.link"
            class="transition-custom relative group"
            :style="{ color: isActiveNav(item.link) ? primaryColor : defaultTextColor }"
            @click.prevent="handleNavClick(item)"
          >
            {{ item.label }}
            <span 
              v-if="isActiveNav(item.link)"
              class="absolute -bottom-1 left-0 w-full h-0.5"
              :style="{ backgroundColor: primaryColor }"
            ></span>
            <span 
              v-else
              class="absolute -bottom-1 left-0 w-0 h-0.5 transition-all duration-300 group-hover:w-full"
              :style="{ backgroundColor: primaryColor }"
            ></span>
          </a>
        </nav>
        
        <!-- 联系按钮 -->
        <a 
          v-if="showActionButton"
          :href="actionButton.link"
          class="hidden items-center px-5 py-2 rounded-lg transition-custom font-medium hidden md:inline-flex"
          :style="getActionButtonStyles()"
          @click.prevent="handleActionButtonClick()"
        >
          {{ actionButton.text }}
          <i class="fa fa-arrow-right ml-2" v-if="actionButton.showIcon"></i>
        </a>
        
        <!-- 移动端菜单按钮 -->
        <button 
          id="menuBtn" 
          class="md:hidden text-dark text-2xl"
          :style="{ color: menuButtonColor }"
          @click="toggleMobileMenu"
        >
          <i class="fa" :class="isMobileMenuOpen ? 'fa-times' : 'fa-bars'"></i>
        </button>
      </div>
    </div>
    
    <!-- 移动端导航菜单 -->
    <div 
      id="mobileMenu" 
      class="md:hidden bg-white border-t transition-all duration-300 overflow-hidden"
      :style="{ 
        maxHeight: isMobileMenuOpen ? '500px' : '0',
        opacity: isMobileMenuOpen ? '1' : '0'
      }"
    >
      <div class="container mx-auto px-4 py-3 space-y-3">
        <a 
          v-for="(item, index) in navItems" 
          :key="index + '_mobile'"
          :href="item.link"
          class="block py-2 transition-custom"
          :style="{ color: isActiveNav(item.link) ? primaryColor : defaultTextColor }"
          @click.prevent="handleMobileNavClick(item)"
        >
          {{ item.label }}
        </a>
        <a 
          v-if="showActionButton"
          :href="actionButton.link"
          class="block py-2 mt-2 rounded-lg text-center transition-custom font-medium"
          :style="getActionButtonStyles()"
          @click.prevent="handleActionButtonClick()"
        >
          {{ actionButton.text }}
        </a>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'Navbar',
  // 低代码平台元数据
  lowcode: {
    meta: {
      name: 'navbar',
      displayName: '导航栏模块',
      description: '网站顶部导航栏，支持响应式布局和滚动效果',
      icon: 'fa-bars',
      category: '导航组件',
      version: '1.0.0',
      isContainer: false
    },
    
    configPanel: [
      {
        title: '基本配置',
        fields: [
          {
            name: 'primaryColor',
            label: '主题色',
            type: 'color',
            defaultValue: '#165DFF'
          },
          {
            name: 'brandName',
            label: '品牌名称',
            type: 'text',
            defaultValue: '智联科技'
          },
          {
            name: 'logoText',
            label: 'Logo',
            type: 'image',
            defaultValue: 'ZL'
          },
          {
            name: 'logoLink',
            label: 'Logo链接',
            type: 'text',
            defaultValue: '#'
          }
        ]
      },
      {
        title: '样式配置',
        fields: [
          {
            name: 'defaultBgColor',
            label: '默认背景色',
            type: 'color',
            defaultValue: 'rgba(255, 255, 255, 0.95)'
          },
          {
            name: 'scrolledBgColor',
            label: '滚动后背景色',
            type: 'color',
            defaultValue: 'rgba(255, 255, 255, 0.98)'
          },
          {
            name: 'scrolledShadow',
            label: '滚动后阴影',
            type: 'text',
            defaultValue: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
          },
          {
            name: 'defaultTextColor',
            label: '默认文本色',
            type: 'color',
            defaultValue: 'rgba(31, 41, 55, 0.8)'
          },
          {
            name: 'logoColor',
            label: 'Logo文本色',
            type: 'color',
            defaultValue: '#1f2937'
          },
          {
            name: 'menuButtonColor',
            label: '菜单按钮色',
            type: 'color',
            defaultValue: '#1f2937'
          }
        ]
      },
      {
        title: '导航项配置',
        fields: [
          {
            name: 'navItems',
            label: '导航项列表',
            type: 'array',
            description: '导航菜单的选项',
            defaultValue: [
              { label: '关于我们', link: '#about' },
              { label: '服务', link: '#services' },
              { label: '产品', link: '#products' },
              { label: '案例', link: '#cases' },
              { label: '团队', link: '#team' },
              { label: '客户评价', link: '#testimonials' },
              { label: '联系我们', link: '#contact' }
            ]
          },
          {
            name: 'activeNavDetection',
            label: '激活项检测方式',
            type: 'select',
            options: [
              { label: '哈希匹配', value: 'hash' },
              { label: '滚动位置', value: 'scroll' }
            ],
            defaultValue: 'hash'
          }
        ]
      },
      {
        title: '按钮配置',
        fields: [
          {
            name: 'showActionButton',
            label: '显示行动按钮',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'actionButton',
            label: '行动按钮配置',
            type: 'object',
            properties: [
              { name: 'text', label: '按钮文本', type: 'text', defaultValue: '立即咨询' },
              { name: 'link', label: '链接地址', type: 'text', defaultValue: '#contact' },
              { name: 'showIcon', label: '显示图标', type: 'boolean', defaultValue: true },
              { name: 'style', label: '按钮样式', type: 'select', options: [
                { label: '填充', value: 'filled' },
                { label: '圆角', value: 'rounded' },
                { label: '扁平', value: 'flat' }
              ], defaultValue: 'filled' }
            ]
          }
        ]
      }
    ],
    
    events: [
      {
        name: 'logoClick',
        label: 'Logo点击',
        description: '点击Logo时触发',
        parameters: [
          { name: 'link', type: 'string', description: 'Logo链接地址' }
        ]
      },
      {
        name: 'navItemClick',
        label: '导航项点击',
        description: '点击导航项时触发',
        parameters: [
          { name: 'item', type: 'object', description: '导航项信息' }
        ]
      },
      {
        name: 'actionButtonClick',
        label: '行动按钮点击',
        description: '点击行动按钮时触发',
        parameters: [
          { name: 'button', type: 'object', description: '按钮配置信息' }
        ]
      },
      {
        name: 'mobileMenuToggle',
        label: '移动端菜单切换',
        description: '移动端菜单展开/收起时触发',
        parameters: [
          { name: 'isOpen', type: 'boolean', description: '菜单是否展开' }
        ]
      },
      {
        name: 'scroll',
        label: '滚动事件',
        description: '页面滚动时触发',
        parameters: [
          { name: 'isScrolled', type: 'boolean', description: '是否滚动超过阈值' },
          { name: 'scrollY', type: 'number', description: '滚动距离' }
        ]
      }
    ],
    
    actions: [
      {
        name: 'setActiveNav',
        label: '设置激活导航项',
        description: '手动设置当前激活的导航项',
        parameters: [
          { name: 'link', type: 'string', required: true, description: '导航项链接' }
        ]
      },
      {
        name: 'toggleMobileMenu',
        label: '切换移动端菜单',
        description: '展开或收起移动端菜单'
      },
      {
        name: 'closeMobileMenu',
        label: '关闭移动端菜单',
        description: '收起移动端菜单'
      },
      {
        name: 'setPrimaryColor',
        label: '设置主题色',
        description: '动态修改导航栏主题色',
        parameters: [
          { name: 'color', type: 'string', required: true, description: '颜色值' }
        ]
      }
    ]
  },
  
  props: {
    // 基本配置
    primaryColor: {
      type: String,
      default: '#165DFF'
    },
    brandName: {
      type: String,
      default: '智联科技'
    },
    logoText: {
      type: String,
      default: 'ZL'
    },
    logoLink: {
      type: String,
      default: '#'
    },
    
    children: {
      type: Array,
      default: () => []
    },
    // 样式配置
    defaultBgColor: {
      type: String,
      default: 'rgba(255, 255, 255, 0.95)'
    },
    scrolledBgColor: {
      type: String,
      default: 'rgba(255, 255, 255, 0.98)'
    },
    scrolledShadow: {
      type: String,
      default: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
    },
    defaultTextColor: {
      type: String,
      default: 'rgba(31, 41, 55, 0.8)'
    },
    logoColor: {
      type: String,
      default: '#1f2937'
    },
    menuButtonColor: {
      type: String,
      default: '#1f2937'
    },
    
    // 导航项配置
    navItems: {
      type: Array,
      default: () => [
        { label: '关于我们', link: '#about' },
        { label: '服务', link: '#services' },
        { label: '产品', link: '#products' },
        { label: '案例', link: '#cases' },
        { label: '团队', link: '#team' },
        { label: '客户评价', link: '#testimonials' },
        { label: '联系我们', link: '#contact' }
      ]
    },
    activeNavDetection: {
      type: String,
      default: 'hash',
      validator: (value) => ['hash', 'scroll'].includes(value)
    },
    scrollThreshold: {
      type: Number,
      default: 50,
      description: '触发导航栏样式变化的滚动阈值'
    },
    
    // 按钮配置
    showActionButton: {
      type: Boolean,
      default: true
    },
    actionButton: {
      type: Object,
      default: () => ({
        text: '立即咨询',
        link: '#contact',
        showIcon: true,
        style: 'filled'
      })
    }
  },
  
  data() {
    return {
      isScrolled: false,
      isMobileMenuOpen: false,
      activeNavLink: ''
    };
  },
  
  mounted() {
    // 初始化激活的导航项
    this.updateActiveNav();
    
    // 监听滚动事件
    window.addEventListener('scroll', this.handleScroll);
    // 监听哈希变化
    window.addEventListener('hashchange', this.updateActiveNav);
    
    // 初始化时检查滚动位置
    this.handleScroll();
  },
  
  beforeUnmount() {
    // 移除事件监听
    window.removeEventListener('scroll', this.handleScroll);
    window.removeEventListener('hashchange', this.updateActiveNav);
  },
  
  methods: {
    /**
     * 处理滚动事件
     */
    handleScroll() {
      const scrollY = window.scrollY;
      this.isScrolled = scrollY > this.scrollThreshold;
      
      // 如果是滚动检测模式，更新激活的导航项
      if (this.activeNavDetection === 'scroll') {
        this.updateActiveNavByScroll();
      }
      
      // 触发滚动事件
      this.$emit('scroll', {
        isScrolled: this.isScrolled,
        scrollY
      });
    },
    
    /**
     * 更新激活的导航项
     */
    updateActiveNav() {
      if (this.activeNavDetection === 'hash') {
        const currentHash = window.location.hash || this.navItems[0].link;
        this.activeNavLink = currentHash;
      } else {
        this.updateActiveNavByScroll();
      }
    },
    
    /**
     * 根据滚动位置更新激活的导航项
     */
    updateActiveNavByScroll() {
      const scrollPosition = window.scrollY + 100;
      
      // 遍历导航项，找到当前可见的区域
      for (let i = this.navItems.length - 1; i >= 0; i--) {
        const item = this.navItems[i];
        if (item.link.startsWith('#') && item.link !== '#') {
          const targetId = item.link.substring(1);
          const targetElement = document.getElementById(targetId);
          
          if (targetElement) {
            const rect = targetElement.getBoundingClientRect();
            const offsetTop = rect.top + window.scrollY;
            
            if (scrollPosition >= offsetTop) {
              this.activeNavLink = item.link;
              break;
            }
          }
        }
      }
    },
    
    /**
     * 判断导航项是否为激活状态
     */
    isActiveNav(link) {
      return this.activeNavLink === link;
    },
    
    /**
     * 切换移动端菜单
     */
    toggleMobileMenu() {
      this.isMobileMenuOpen = !this.isMobileMenuOpen;
      this.$emit('mobileMenuToggle', {
        isOpen: this.isMobileMenuOpen
      });
    },
    
    /**
     * 关闭移动端菜单
     */
    closeMobileMenu() {
      if (this.isMobileMenuOpen) {
        this.isMobileMenuOpen = false;
        this.$emit('mobileMenuToggle', {
          isOpen: false
        });
      }
    },
    
    /**
     * 处理Logo点击
     */
    handleLogoClick() {
      this.$emit('logoClick', {
        link: this.logoLink
      });
      
      // 执行跳转
      if (this.logoLink.startsWith('#')) {
        const targetId = this.logoLink.substring(1);
        if (targetId) {
          const targetElement = document.getElementById(targetId);
          if (targetElement) {
            targetElement.scrollIntoView({ behavior: 'smooth' });
          }
        } else {
          // 回到顶部
          window.scrollTo({ top: 0, behavior: 'smooth' });
        }
      } else {
        window.location.href = this.logoLink;
      }
      
      this.closeMobileMenu();
    },
    
    /**
     * 处理导航项点击
     */
    handleNavClick(item) {
      this.$emit('navItemClick', {
        item
      });
      
      // 更新激活状态
      this.activeNavLink = item.link;
      
      // 执行跳转
      if (item.link.startsWith('#')) {
        const targetId = item.link.substring(1);
        const targetElement = document.getElementById(targetId);
        if (targetElement) {
          targetElement.scrollIntoView({ behavior: 'smooth' });
        }
      } else {
        window.location.href = item.link;
      }
      
      this.closeMobileMenu();
    },
    
    /**
     * 处理移动端导航项点击
     */
    handleMobileMobileNavClick(item) {
      this.handleNavClick(item);
    },
    
    /**
     * 处理行动按钮点击
     */
    handleActionButtonClick() {
      this.$emit('actionButtonClick', {
        button: this.actionButton
      });
      
      // 执行跳转
      if (this.actionButton.link.startsWith('#')) {
        const targetId = this.actionButton.link.substring(1);
        const targetElement = document.getElementById(targetId);
        if (targetElement) {
          targetElement.scrollIntoView({ behavior: 'smooth' });
        }
      } else {
        window.location.href = this.actionButton.link;
      }
      
      this.closeMobileMenu();
    },
    
    /**
     * 获取     * 设置激活的导航项
     */
    setActiveNav(link) {
      this.activeNavLink = link;
    },
    
    /**
     * 设置主题色
     */
    setPrimaryColor(color) {
      this.primaryColor = color;
    },
    
    /**
     * 获取行动按钮样式
     */
    getActionButtonStyles() {
      const baseStyles = {};
      
      switch (this.actionButton.style) {
        case 'filled':
          baseStyles.backgroundColor = this.primaryColor;
          baseStyles.color = '#ffffff';
          baseStyles['--hover-bg'] = this.getColorWithOpacity(this.primaryColor, 0.9);
          baseStyles.borderRadius = '8px';
          break;
        case 'rounded':
          baseStyles.backgroundColor = this.primaryColor;
          baseStyles.color = '#ffffff';
          baseStyles['--hover-bg'] = this.getColorWithOpacity(this.primaryColor, 0.9);
          baseStyles.borderRadius = '30px';
          break;
        case 'flat':
          baseStyles.backgroundColor = 'transparent';
          baseStyles.color = this.primaryColor;
          baseStyles.border = `1px solid ${this.primaryColor}`;
          baseStyles['--hover-bg'] = this.getColorWithOpacity(this.primaryColor, 0.1);
          baseStyles.borderRadius = '8px';
          break;
      }
      
      return baseStyles;
    },
    
    /**
     * 辅助方法：获取带透明度的颜色
     */
    getColorWithOpacity(color, opacity) {
      if (color.startsWith('#') && color.length === 7) {
        const alpha = Math.round(opacity * 255).toString(16).padStart(2, '0');
        return `${color}${alpha}`;
      }
      return color;
    }
  }
};
</script>

<style scoped>
/* 按钮悬停样式 */
a[style*="--hover-bg"]:hover {
  background-color: var(--hover-bg) !important;
}

/* 导航项动画 */
.group-hover\:w-full {
  width: 0;
}

.group:hover .group-hover\:w-full {
  width: 100%;
}

/* 移动端菜单过渡 */
#mobileMenu {
  transition: max-height 0.3s ease, opacity 0.3s ease;
}

/* 导航项下划线动画 */
nav a span {
  transition: width 0.3s ease;
}
</style>
    